import router from './router'
import { ElMessage } from 'element-plus'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isHttp } from '@/utils/validate'
import { isRelogin } from '@/utils/request'
import useUserStore from '@/store/modules/user'
import useSettingsStore from '@/store/modules/settings'
import usePermissionStore from '@/store/modules/permission'
import useTagsViewStore from '@/store/modules/tagsView'
import {ebaykdToken} from '@/api/system/index.js'
import tabs from '@/qiankun/tabs'


NProgress.configure({ showSpinner: false });

const whiteList = ['/login', '/register'];
const uuid = window.location.search.split('uuid=') ? window.location.search.split('uuid=')[1] : ''
if (uuid) { sessionStorage.setItem("uuid", JSON.stringify(uuid)) }
router.beforeEach((to, from, next) => {
  NProgress.start()

  let current = window.location.pathname.split('/')
  if (current.length && current[1] === current[2]) {
    current = current.splice(2).join('/')
    current = current.startsWith('/') ? current : '/' + current
    history.replaceState({back: from.path, current: window.location.pathname + window.location.search}, to.name, current)
  } else {
    history.replaceState({back: from.href, current: window.location.pathname + window.location.search}, to.name, '')
  }

  const { meta } = to
  if (!meta.moduleName) {
    const routes = router.getRoutes()
    const moduleName = (routes.find(d => d.path.indexOf(to.path) > -1))?.meta?.moduleName
    if (moduleName) {
      to.path = `/${moduleName}${to.path}`
      to.href = `/${moduleName}${to.path}`
      to.fullPath = `/${moduleName}${to.fullPath}`
      to.meta.moduleName = moduleName
      next({ ...to, replace: true })
      return
    }
  }

  // permissionStore.setCurrentModule(to.meta.moduleName)
  // permissionStore.setCurrentPage(to.path)
  if (getToken()) {
    if (to.href.includes("sys=ebay_kd")) {
      ebaykdToken().then(res => {
        window.location.href = res.data
      })
      return
    }

    to.meta.title && useSettingsStore().setTitle(to.meta.title)
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      if (useUserStore().roles.length === 0) {
        isRelogin.show = true
        // 判断当前用户是否已拉取完user_info信息
        useUserStore().getInfo().then(() => {
          isRelogin.show = false
          usePermissionStore().generateRoutes().then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            accessRoutes.forEach(route => {
              if (!isHttp(route.path)) {
                if (!route.path.startsWith("/")) {
                  route.path = `/${route.path}`;
                }
                router.addRoute(route) // 动态添加可访问路由表
              }
            })
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        }).catch(err => {
          // 不退出登陆 2024-3-1
          // console.warn(err)
          // useUserStore().logOut().then(() => {
          //   ElMessage.error(err)
          //   next({ path: '/' })
          // }).catch((e)=> {
          //   console.error(e)
          //   next({ path: '/' })
          // })

          isRelogin.show = false
          usePermissionStore().generateRoutes().then(accessRoutes => {
            // 根据roles权限生成可访问的路由表
            accessRoutes.forEach(route => {
              if (!isHttp(route.path)) {
                if (!route.path.startsWith("/")) {
                  route.path = `/${route.path}`;
                }
                router.addRoute(route) // 动态添加可访问路由表
              }
            })
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          })
        })
      } else {
        let routeModuleName = to.path.split("/")[1]
        if(to.path.includes(`/${routeModuleName}/${routeModuleName}/`)){
          console.warn('----------  出现路由重复问题  ----------',to.path);
          return
        }else{
          useTagsViewStore().addFromView(from)
          tabs.openTab({
            ...to,
            next
          })
        }

        NProgress.done()
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}&uuid=${JSON.parse(sessionStorage.getItem('uuid'))}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
